package com.hangzhou.xyj.ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.db.preferences.CommonPreferences;
import com.hangzhou.xyj.event.AnimationEvent;
import com.hangzhou.xyj.event.CacheProgressEvent;
import com.hangzhou.xyj.event.OperationRespEvent;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.manager.ScreenManager;
import com.hangzhou.xyj.model.CommentPageInfoModel;
import com.hangzhou.xyj.model.DianDramaModel;
import com.hangzhou.xyj.model.DramaModel;
import com.hangzhou.xyj.model.DynamicDetailModel;
import com.hangzhou.xyj.model.UserModel;
import com.hangzhou.xyj.model.type.EFileType;
import com.hangzhou.xyj.model.type.EIntentTagType;
import com.hangzhou.xyj.model.type.EPlayControlType;
import com.hangzhou.xyj.net.handler.GetCommentListHandler;
import com.hangzhou.xyj.net.handler.GetDynamicDetailHandler;
import com.hangzhou.xyj.net.handler.ReportHandler;
import com.hangzhou.xyj.net.handler.TransferHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.listener.HttpResponseListener;
import com.hangzhou.xyj.net.request.GetCommentListReq;
import com.hangzhou.xyj.net.request.GetDynamicDetailReq;
import com.hangzhou.xyj.net.request.ReportReq;
import com.hangzhou.xyj.net.request.TransferReq;
import com.hangzhou.xyj.ui.adapter.DramaPlayAdapter;
import com.hangzhou.xyj.ui.listener.DownAudioListener;
import com.hangzhou.xyj.ui.widget.CommonActionView;
import com.hangzhou.xyj.ui.widget.SelectMenuDialog;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.EventBusUtil;
import com.hangzhou.xyj.utils.LogUtil;
import com.hangzhou.xyj.utils.PublicUtil;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;
import com.hangzhou.xyj.utils.constants.AppConstants;
import com.hangzhou.xyj.utils.constants.DataKey;
import com.mediaideas.videoengine.lyrics.LrcView;
import com.mediaideas.videoengine.utils.MusicUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;

/**
 * Created by neo.duan on 2016/1/17.
 * 戏曲播放界面
 */
public class DramaPlayActivity extends BasePlayActivity implements View.OnClickListener, DramaPlayAdapter.OnPlayStatusChangedListener
        , BasePlayActivity.OnMediaPlayerCompleteListener, DramaPlayAdapter.OnRefreshDataListenter, BasePlayActivity.OnServiceConnectedListener {
    private final static String TAG = "DramaPlayActivity";
    TextView playTotalTimeTV;
    TextView currentPlayTimeTV;
    SeekBar seekBar;
    private RecyclerView mRecyclerView;
    private Button mBtnBack;//返回按钮
    private ImageButton mBtnMore;//菜单按钮
    private int mAlpha;//初始化透明度的值，默认完全透明
    private RelativeLayout mRlTopBar;//标题栏
    //    private String mDefaultFilePath;
    private MyTextView mTvSongName;//标题栏的歌曲名称
    private int flag = 0;//标志位：0，用的是白色图；1，用的是黑色图
    private DramaPlayAdapter mAdapter;
    private int mCommentObjId;//评论对象的Id
    private String mDramaId; //戏曲ID
    private String mNextDramaId;//下一首ID
    private String mPreviousDramaId;//上一首ID
    private DynamicDetailModel mDramaInfo;
    private DianDramaModel mDianDramaModel;//当前正在播放的戏曲model
    private DynamicDetailModel mNextDramaInfo;
    private DianDramaModel mNextDianDramaModel;//下一首戏曲model
    private DynamicDetailModel mPreviousDramaInfo;
    private DianDramaModel mPreviousDianDramaModel;//上一首戏曲model
    private List<DramaModel> mDramaList; //别的页面传递过来的戏曲集合，用于播放上一首下一首
    private DramaModel mDramaModel;
    private int mDramaPos; //当前播放戏曲的位置
    private RelativeLayout mLlMenu;//更多菜单
    private EIntentTagType mIntentTag;//区分是从哪个页面进来的
    private CommonActionView mActionView;//下方的横条
    private String mShareContent;
    private String mShareUrl;
    private String mShareName;
    private boolean isFirst = true;//是否是第一次点击播放按钮
    private boolean isSame = false;//是否相同歌曲
    private boolean isPick = false;//是否切歌（上一首，下一首，自动到下一首）
    private String realNativeUrl;//真正的原唱的url

    private boolean isFinishGetData;//是否获取完数据
    private boolean isServiceConnected;//服务是否连接完成
    /**
     * 下载音频监听器
     */
    private DownAudioListener mAudioDownListener = new DownAudioListener() {
        @Override
        public void onDownAudioStart(int audioType) {
            LogUtil.d(TAG, "down audio start");
        }

        @Override
        public void onDownAudioComplete(int audioType) {
            LogUtil.d(TAG, "down audio complete");
/*            //下载原唱完成，开始播放音频
            if (audioType == AUDIO_NATIVE) {
                startPlayback(PublicUtil.getFilePath(mDianDramaModel.getNativeUrl(), EFileType.AUDIO));
            }*/
        }

        @Override
        public void onDownloading(int progress) {
            if (progress > 10)
                startPlayback(PublicUtil.getFilePath(mDianDramaModel.getNativeUrl(), EFileType.AUDIO));
        }

        @Override
        public void onDownAudioFail(int audioType) {
            LogUtil.d(TAG, "down audio fail");
        }
    };

    @Override
    public void onRefreshData() {
        if (isSame /*&& !isPick*/) {
            //刷新数据的时候
//            mAdapter.initPalyState(AppConstants.CURRENT_PLAY_STATE);
            setIsPlayingRightDrama(true);
            long next = startRefreshProgressHint();
            sendNextRefreshMessage(next);
        }
    }

    @Override
    public void initTop() {
        enableTop(false);
        registerEventBus();
    }

    @Override
    public void initIntentData(Intent intent) {
        mDramaList = (List<DramaModel>) intent.getSerializableExtra(DataKey.DRAMA_LIST);
        mDramaPos = intent.getIntExtra(DataKey.DRAMA_POSITION, 0);
        mIntentTag = EIntentTagType.valueOf(intent.getIntExtra(DataKey.INTENT_TAG, -1));
        if (mIntentTag == EIntentTagType.TAG_PLAY_RESTORE && AppConstants.CURRENT_TAG_TYPE != null) {
            mIntentTag = EIntentTagType.TAG_STAGE_EXPERT;//名家作品 恢复播放界面
        }
        //重置
        AppConstants.PLAY_LIST = mDramaList;
        AppConstants.CURRENT_PLAY_POSITION = mDramaPos;
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_drama_play);
    }

    @Override
    public void initViews() {
        mBtnBack = findView(R.id.btn_back);
        mBtnMore = findView(R.id.btn_more);
        mLlMenu = findView(R.id.rl_drama_play_more);

        mRlTopBar = (RelativeLayout) findViewById(R.id.ll_top_bar);
        mActionView = findView(R.id.cav_drama_play);
        mTvSongName = findView(R.id.tv_song_name);
        mRecyclerView = findView(R.id.rc_drama_play);
        //设置水平布局
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        // 设置item动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new DramaPlayAdapter(mContext));

        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager llm = (LinearLayoutManager) recyclerView.getLayoutManager();
                View view = llm.findViewByPosition(0);//获得播放器的View
                if (llm.findFirstVisibleItemPosition() == 0) {
                    float top = -(float) view.getTop();
                    float rate = top / (float) view.getHeight();
                    ImageView IvPlay = getIVPlayView();
                    if (IvPlay != null) {
                        IvPlay.setImageResource(hasPlaying() ? R.drawable.ic_drama_pause : R.drawable.ic_drama_playing);
                    }
                    if (rate < 0.5) { //页面下滑
                        if (flag == 1) {
                            flag = 0;
                            mBtnBack.setBackgroundResource(R.drawable.ic_return_white);
                            mBtnMore.setImageResource(R.drawable.ic_more_white);
                        }
                        mRlTopBar.getBackground().mutate().setAlpha((int) (rate * 255));//浅变深
                        mTvSongName.setTextColor(Color.argb((int) ((1 - rate * 2) * 255), 255, 255, 255));//深变浅，2倍速度
                        mBtnBack.getBackground().mutate().setAlpha((int) ((1 - rate * 2) * 255));
                        mBtnMore.setAlpha((int) ((1 - rate * 2) * 255));
                    } else if (rate >= 0.5 && rate <= 0.7) { //页面上滑
                        if (flag == 0) {
                            flag = 1;
                            mBtnBack.setBackgroundResource(R.drawable.ic_return_arrow);
                            mBtnMore.setImageResource(R.drawable.ic_action_menu);
                        }
                        mRlTopBar.getBackground().mutate().setAlpha((int) ((rate + 0.3) * 255));
                        mTvSongName.setTextColor(Color.argb((int) ((2 * (rate + 0.3) - 1) * 255), 44, 18, 0));
                        mBtnBack.getBackground().mutate().setAlpha((int) ((2 * (rate + 0.3) - 1) * 255));
                        mBtnMore.setAlpha((int) ((2 * (rate + 0.3) - 1) * 255));
                    } else {
                        mRlTopBar.getBackground().mutate().setAlpha(255);
                        mTvSongName.setTextColor(Color.argb(255, 44, 18, 0));
                        mBtnBack.getBackground().mutate().setAlpha(255);

                        mBtnMore.setAlpha(255);
                    }
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });

    }

    @Override
    public void initDatas() {
        if (!isPick) {
            setPlayEnable(false);//播放按钮不可用
        }
        if (mIntentTag == EIntentTagType.TAG_STAGE_EXPERT) {//如果 名家作品 进入
            mLlMenu.setVisibility(View.GONE);
            mActionView.setVisibility(View.GONE);
            mAdapter.setIntentTag(mIntentTag);
            AppConstants.CURRENT_TAG_TYPE = mIntentTag;
        } else {
            if (StringUtil.isNotEmpty(AppConstants.PLAYING_DRAMA_ID)) {
                mActionView.setActionId(Integer.valueOf(AppConstants.PLAYING_DRAMA_ID));
            }
        }
        if (mHandler == null) {
            mHandler = new MsgHandler(this);
        }
        //当前播放的戏曲
        if (mDramaList != null && mDramaList.size() > mDramaPos) {  //10  9

            mDramaId = mDramaList.get(mDramaPos).getId() + "";

            //没有上一个了
            if (mDramaPos - 1 < 0) {
                mPreviousDramaId = mDramaList.get(mDramaList.size() - 1).getId() + "";//取最后一个
            } else {
                mPreviousDramaId = mDramaList.get(mDramaPos - 1).getId() + "";
            }

            //还有下一个
            if (mDramaPos < mDramaList.size() - 1) {
                mNextDramaId = mDramaList.get(mDramaPos + 1).getId() + "";
            } else {
                mNextDramaId = mDramaList.get(0).getId() + "";//取第一个
            }

            //默认当前播放为
            if (AppConstants.PLAYING_DRAMA_ID.equals(mDramaId)) {//如果当前播放的 和 进来的是相等的
                isSame = true;
            } else {
                isSame = false;
                AppConstants.PLAYING_DRAMA_ID = mDramaId;//设置当前播放ID
                AppConstants.CURRENT_PLAY_POSITION = mDramaPos;
                mActionView.setActionId(Integer.valueOf(AppConstants.PLAYING_DRAMA_ID));
            }
        }
        if (isFirst) {//第一次进来的时候
            isFirst = false;
            getDramaInfo(false, Integer.valueOf(mDramaId), 2);
        }
        getCommentList(1);
    }


    private void getNativeUrl(String baseId) {
        if ("0".equals(baseId)) {
            return;
        }
        GetDynamicDetailReq req;
        if (XYJApplication.getUserInfo() != null) {
            String userId = XYJApplication.getUserInfo().getUserId();
            req = new GetDynamicDetailReq(Integer.valueOf(baseId), Integer.valueOf(userId));
        } else {
            req = new GetDynamicDetailReq(baseId);
        }
        HttpLoader.getInstance().sendRequest(new GetDynamicDetailHandler(req, new HttpResponseListener() {
            @Override
            public void onSuccess(Object model) {
                DynamicDetailModel tempDetailModel = (DynamicDetailModel) model;
                realNativeUrl = tempDetailModel.getNative_url();
            }

            @Override
            public void onDone(String msg) {

            }

            @Override
            public void onStart() {

            }

            @Override
            public void onFail(String msg) {

            }

            @Override
            public void onError() {

            }
        }, 0));
    }


    /**
     * 播放完成之后
     */
    @Override
    public void onMediaPlayerComplete() {
        onPlayNext(null);//下一首
    }

    /**
     * 获取戏曲详情
     *
     * @param pos 2:当前播放的曲目信息；1：上一首；3：下一首
     */
    private void getDramaInfo(final boolean isUpdateNum, int dramaId, final int pos) {
        GetDynamicDetailReq req;
        if (XYJApplication.getUserInfo() != null) {
            String userId = XYJApplication.getUserInfo().getUserId();
            req = new GetDynamicDetailReq(dramaId, Integer.valueOf(userId));
        } else {
            req = new GetDynamicDetailReq(dramaId);
        }
        HttpLoader.getInstance().sendRequest(new GetDynamicDetailHandler(req, new HttpResponseListener() {
            @Override
            public void onSuccess(Object model) {
                DynamicDetailModel tempDetailModel = (DynamicDetailModel) model;
                if (tempDetailModel != null) {
                    //组装戏曲类
                    DianDramaModel tempModel = new DianDramaModel();
                    tempModel.setName(tempDetailModel.getName());
                    tempModel.setId((int) tempDetailModel.getId());
                    tempModel.setNativeUrl(tempDetailModel.getNative_url());
                    tempModel.setAccompanyUrl(tempDetailModel.getAccompany_url());
                    tempModel.setLrcUrl(tempDetailModel.getLyric_url());
                    tempModel.setUserId(tempDetailModel.getUserId() + "");
                    tempModel.setHead(tempDetailModel.getUserHead());
                    tempModel.setAuthor(tempDetailModel.getNickname());
                    Log.d("debug", "获取到曲目信息了");
                    switch (pos) {
                        case 1://上一首
                            mPreviousDianDramaModel = tempModel;
                            mPreviousDramaInfo = tempDetailModel;
                            getDramaInfo(false, Integer.valueOf(mNextDramaId), 3);//下载下一首
                            break;
                        case 2://请求的是当前播放的曲目的时候
                            if (isUpdateNum) {
                                mAdapter.updatePersonInfoNum(tempDetailModel);
                            } else {
                                Log.d("debug", "已经获取到曲目信息，准备播放");
                                mDianDramaModel = tempModel;
                                mDramaInfo = tempDetailModel;
                                mCommentObjId = Integer.valueOf(mDianDramaModel.getUserId());
                                isFinishGetData = true;
                                Log.d("debug", "isSame = " + isSame + "当前状态" + AppConstants.CURRENT_PLAY_STATE);
                                if (isSame && AppConstants.CURRENT_PLAY_STATE == EPlayControlType.PLAY) {//恢复
                                    Log.d("debug", "恢复播放");
                                    refreshSeekBar();
                                    setPlayEnable(true);
                                    //初始化界面
                                    initPlayback();
                                    startLrcPlay();
                                    //填充个人信息页面的数据
                                    mAdapter.updatePersonInfo(mDramaInfo);
                                    //获取上一首与下一首，提前缓存好
                                    getDramaInfo(false, Integer.valueOf(mPreviousDramaId), 1);
                                } else {
                                    doWhenStartPlayBack();
                                }
                            }
                            break;
                        case 3://下一首
                            mNextDianDramaModel = tempModel;
                            mNextDramaInfo = tempDetailModel;
                            getNativeUrl(mDramaInfo.getBaseId());
                            break;
                    }
                }
                setGoToNextEnable(true);
                setGoToPreviousEnable(true);
            }

            @Override
            public void onDone(String msg) {

            }

            @Override
            public void onStart() {

            }

            @Override
            public void onFail(String msg) {
                AppConstants.PLAY_LIST.remove(mDramaPos);
                if (AppConstants.PLAY_LIST.size() == 0) {
                    ToastUtil.show("该条记录已被删除，播放列表已为空！");
                    ScreenManager.getInstance().currentActivity().finish();
                    return;
                } else {
                    ToastUtil.show("该条记录已被删除，开始播放下一首");
                }
                //还有下一个
                if (mDramaPos < mDramaList.size() - 1) {
                    mDramaPos = mDramaPos + 1;
                } else {
                    mDramaPos = 0;
                }
                try {
                    mService.stop();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                AppConstants.PLAYING_DRAMA_ID = "";
                isFirst = true;
                initDatas();
            }

            @Override
            public void onError() {
            }
        }, 0));
    }

    private void doWhenStartPlayBack() {
        if (isFinishGetData && isServiceConnected) {
            isFinishGetData = false;
            Log.d("debug", "播放ing");
            startPlayback(mDianDramaModel.getNativeUrl());//开始播放
            EventBusUtil.postEvent(new AnimationEvent(true));//左上角动画 启动
            refreshSeekBar();
            sendPlayCount();
            setPlayEnable(true);
            //初始化界面
            initPlayback();
            //填充个人信息页面的数据
            mAdapter.updatePersonInfo(mDramaInfo);
            //获取上一首与下一首，提前缓存好
            getDramaInfo(false, Integer.valueOf(mPreviousDramaId), 1);
        }
    }

    @Override
    public void onServiceConnected() {//服务连接完成
        isServiceConnected = true;
        doWhenStartPlayBack();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        isFirst = true;
        this.initIntentData(intent);
        this.initDatas();
    }

    /**
     * 下载歌曲 和 伴奏
     */
    private void downloadLyric() {
        //下载歌词
        if (StringUtil.isNotEmpty(mDramaId)) {
            super.downloadLyric(mDianDramaModel.getLrcUrl());
        }
    }

    @Subscribe
    public void onEventMainThread(OperationRespEvent event) {
        if (event.isSuccess()) {
            getCommentList(1);
            getDramaInfo(true, Integer.valueOf(mDramaId), 2);
        }
    }

    /**
     * 分享之后调用，用于统计分享的次数
     *
     * @param type  1：活动、演出，热点； 2：社群；
     * @param objId 被分享的对象的ID
     * @return
     * @author yaohuix
     * @date 2016/5/5 16:21
     */
    public void afterTransFer(int objId, int type) {
        TransferReq transferReq = new TransferReq(objId, type, mMyUserId);
        HttpLoader.getInstance().sendRequest(new TransferHandler(transferReq, new MyHttpResponseListener() {
            @Override
            public void onSuccess(Object model) {
                super.onSuccess(model);
            }
        }, 0));
    }

    @Override
    public void initListeners() {
        findView(R.id.rl_drama_play_back).setOnClickListener(this);
        findView(R.id.rl_drama_play_more).setOnClickListener(this);
        mAdapter.setOnNumChangeListener(new DramaPlayAdapter.OnNumChangeListener() {
            @Override
            public void onNumchange() {
                getDramaInfo(true, Integer.valueOf(mDramaId), 2);
            }
        });
        mActionView.setOnBtnShareClickListener(new CommonActionView.OnBtnShareClickListener() {
            @Override
            public void OnBtnShareClick() {
                PublicUtil.showShareContent(mShareName, mShareContent, mShareUrl, new PlatformActionListener() {
                    @Override
                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                        afterTransFer(Integer.valueOf(mDramaId), 2);
//                        getDramaInfo(true);
                    }

                    @Override
                    public void onError(Platform platform, int i, Throwable throwable) {

                    }

                    @Override
                    public void onCancel(Platform platform, int i) {

                    }
                });
            }
        });
        setOnDownAudioListener(mAudioDownListener);
        setOnMediaPlayerCompleteListener(this);
        mAdapter.setOnRefreshDataListenter(this);
        mAdapter.setOnSingClickListener(new DramaPlayAdapter.OnSingClickListener() {
            @Override
            public void OnSingClick() {
                //暂停播放
                pausePlayback();
                AppConstants.CURRENT_PLAY_STATE = EPlayControlType.PAUSE;
                ScreenManager.getInstance().currentActivity().finish();
            }
        });
        mAdapter.setOnPlayStatusChangedListener(this);
        setOnServiceConnectedListener(this);
//        getDramaInfo(false,m);
    }


    /**
     * 处理戏曲缓冲进度
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(CacheProgressEvent event) {
        if (event == null) {
            return;
        }
        //缓存进度
        int progress = event.getProgress();
        //找到SeekBar，设置进度値
        RecyclerView.ViewHolder viewHolder = mRecyclerView.findViewHolderForAdapterPosition(0);
        if (viewHolder instanceof DramaPlayAdapter.DramaPlayViewHolder) {
            SeekBar seekBar = ((DramaPlayAdapter.DramaPlayViewHolder) viewHolder).mSeekBar;
            seekBar.setSecondaryProgress(progress);
        }
    }

    protected DramaPlayAdapter.DramaPlayViewHolder getDramaPlayViewHolder() {
        RecyclerView.ViewHolder viewHolder = mRecyclerView.findViewHolderForLayoutPosition(0);
        if (viewHolder instanceof DramaPlayAdapter.DramaPlayViewHolder) {
            return ((DramaPlayAdapter.DramaPlayViewHolder) viewHolder);
        }
        return null;
    }

    protected TextView getCurrentPlayTimeView() {
        DramaPlayAdapter.DramaPlayViewHolder holder = getDramaPlayViewHolder();
        if (holder != null) {
            return holder.mTvCurrentTime;
        }
        return null;
    }

    /**
     * 设置 下一首按钮 是否可用
     *
     * @param enable
     */
    private void setGoToNextEnable(boolean enable) {
        DramaPlayAdapter.DramaPlayViewHolder holder = getDramaPlayViewHolder();
        if (holder != null) {
            holder.mIvNext.setEnabled(enable);
        }
    }

    /**
     * 设置 播放按钮 是否可用
     *
     * @param enable
     */
    private void setPlayEnable(boolean enable) {
        DramaPlayAdapter.DramaPlayViewHolder holder = getDramaPlayViewHolder();
        if (holder != null) {
            holder.mIvPlay.setEnabled(enable);
        }
    }

    /**
     * 设置 上一首 按钮是否可用
     *
     * @param enable
     */
    private void setGoToPreviousEnable(boolean enable) {
        DramaPlayAdapter.DramaPlayViewHolder holder = getDramaPlayViewHolder();
        if (holder != null) {
            holder.mIvPrevious.setEnabled(enable);
        }
    }

    protected LrcView getLrcView() {
        DramaPlayAdapter.DramaPlayViewHolder holder = getDramaPlayViewHolder();
        if (holder != null) {
            return holder.mLrcView;
        }
        return null;
    }

    protected ImageView getIVPlayView() {
        DramaPlayAdapter.DramaPlayViewHolder holder = getDramaPlayViewHolder();
        if (holder != null) {
            return holder.mIvPlay;
        }
        return null;
    }

    protected TextView getPlayTotalTimeView() {
        DramaPlayAdapter.DramaPlayViewHolder holder = getDramaPlayViewHolder();
        if (holder != null) {
            return holder.mTvTotalTime;
        }
        return null;
    }

    protected SeekBar getDramaPlaySeekBar() {
        DramaPlayAdapter.DramaPlayViewHolder holder = getDramaPlayViewHolder();
        if (holder != null) {
            return holder.mSeekBar;
        }
        return null;
    }

    @Override
    public void onPlayClick(View view, EPlayControlType type) {
        switch (type) {
            case PLAY://播放
                restartPlayBack();
                break;
            case PAUSE://暂停
                pausePlayback();
                break;
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress) {
        if (seekBar != null) {
            seekTo(progress * mDuration / 1000);
        }
    }

    //上一首
    @Override
    public void onPlayPrevious(View view) {
        setGoToPreviousEnable(false);//暂时不可以点击
        if (mDramaPos == 0) {
            //没有上一首,取最后一首
            mDramaPos = mDramaList.size() - 1;
        } else {
            mDramaPos--;
        }
        mDianDramaModel = mPreviousDianDramaModel;
        mDramaInfo = mPreviousDramaInfo;
        isPick = true;
        isSame = false;
        restorePlayState();
        if (mAdapter.menuDialog != null && mAdapter.menuDialog.isShowing()) {
            mAdapter.menuDialog.dismiss();
        }
    }

    //下一首
    @Override
    public void onPlayNext(View view) {
        setGoToNextEnable(false);//下一首按钮不可用
        if (mDramaPos == mDramaList.size() - 1) {
            //没有了下一首，取第一首
            mDramaPos = 0;
        } else {
            mDramaPos++;
        }
        mDianDramaModel = mNextDianDramaModel;
        mDramaInfo = mNextDramaInfo;
        isPick = true;
        isSame = false;
        restorePlayState();
        if (mAdapter.menuDialog != null && mAdapter.menuDialog.isShowing()) {
            mAdapter.menuDialog.dismiss();
        }
    }

    private void restorePlayState() {
        mCommentObjId = Integer.valueOf(mDianDramaModel.getUserId());
        initDatas();
        if (isPick) {
            isPick = false;
            startPlayback(mDianDramaModel.getNativeUrl());//开始播放
            sendPlayCount();
            EventBus.getDefault().post(new AnimationEvent(true));//左上角动画 启动
            refreshSeekBar();
            //初始化界面
            initPlayback();
        }
        mAdapter.updatePersonInfo(mDramaInfo);//初始化个人信息条
        //获取上一首与下一首，提前缓存好
        getDramaInfo(false, Integer.valueOf(mPreviousDramaId), 1);
    }

    /**
     * 刷新 时间显示 并返回时间间隔（每隔多少时间 刷新）
     *
     * @param
     * @return long 时间间隔
     * @author yaohuix
     * @date 2016/5/11 18:03
     */
    @Override
    protected long startRefreshProgressHint() {
        if (mService == null
                || getCurrentPlayTimeView() == null
                || getPlayTotalTimeView() == null
                || getDramaPlaySeekBar() == null) {
            return 500;
        }
        try {
            long position = mService.position();
            if (playTotalTimeTV == null)
                playTotalTimeTV = getPlayTotalTimeView();
            if (currentPlayTimeTV == null)
                currentPlayTimeTV = getCurrentPlayTimeView();
            if (seekBar == null)
                seekBar = getDramaPlaySeekBar();
            if (position >= 0 && mDuration > 0) {
                currentPlayTimeTV.setText(MusicUtils.makeTimeString(this, position / 1000));
                playTotalTimeTV.setText(MusicUtils.makeTimeString(this, mDuration / 1000));
                int progress = (int) (1000 * position / mDuration);
                seekBar.setProgress(progress);
            } else {
                currentPlayTimeTV.setText("0:00");
                playTotalTimeTV.setText(MusicUtils.makeTimeString(this, mDuration / 1000));
                seekBar.setProgress(0);
            }
            // calculate the number of milliseconds until the next full second, so
            // the counter can be updated at just the right time
            long remaining = 1000 - (position % 1000);

            // approximate how often we would need to refresh the slider to
            // move it smoothly
            int width = seekBar.getWidth();
            if (width == 0) width = 320;
            long smoothrefreshtime = mDuration / width;

            if (smoothrefreshtime > remaining) return remaining;
            if (smoothrefreshtime < 20) return 20;
            return smoothrefreshtime;
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return 500;
    }

    @Override
    protected void onResume() {
        super.onResume();
//        playTotalTimeTV = getPlayTotalTimeView();
//        Log.d("debug", "还未空？？？？？" + playTotalTimeTV);
//        currentPlayTimeTV = getCurrentPlayTimeView();
//        seekBar = getDramaPlaySeekBar();
//        Log.d("debug", "这里是resume");
//        try {
//            if (mService != null)
//                Log.d("debug", "当前播放url" + mService.getPath() + "当前播放总时长：" + (AppConstants.CURRENT_DURATION / 1000) + "当前播放位置：" + mService.position());
//        } catch (RemoteException e) {
//            e.printStackTrace();
//        }
        if (isMusicPlaying()) {//恢复
//            mAdapter.initPalyState(AppConstants.CURRENT_PLAY_STATE);
            refreshSeekBar();
        } /*else {
            if (mService != null) {
                startRefreshProgressHint();//恢复进度条
            }
        }*/
    }

    /**
     * 初始化播放界面 获取歌词，获取音频总时长显示
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/5/12 17:12
     */

    private void initPlayback() {
        try {
            mLrcView = getLrcView();
            downloadLyric();
            //设置分享的内容
            mShareContent = mDramaInfo.getContent();
            mShareUrl = mDramaInfo.getShareUrl();
            mShareName = mDianDramaModel.getName();
            mTvSongName.setText(mDianDramaModel.getName());
            mDuration = mService.duration();
            //获取当前的位置
            long position;
            if (isSame) {
                position = mService.position();//当前位置
            } else {
                position = 0;
            }
            if (isSame && !isMusicPlaying()) {
                position = AppConstants.CURRENT_POSITION;
                mDuration = AppConstants.CURRENT_DURATION;
                mService.openFile(AppConstants.CURRENT_URL);
                mService.seek(AppConstants.CURRENT_POSITION);
            }
            //当前进度
            int progress = (int) (1000 * position / mDuration);
            if (playTotalTimeTV != null) {//总的时长
                playTotalTimeTV.setText(MusicUtils.makeTimeString(this, mDuration / 1000));
            }
            if (currentPlayTimeTV != null) {//当前时长位置
                currentPlayTimeTV.setText(MusicUtils.makeTimeString(this, position / 1000));
            }
            if (seekBar != null) {//设置进度条
                seekBar.setProgress(progress);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 开始播放
     *
     * @param filePath
     */
    @Override
    protected void startPlayback(String filePath) {
        if (mService == null) {
            Log.d("debug", "mService 为空，所以没有播放？");
            return;
        }
        try {
            Log.d("debug", "开始播放新的" + filePath);
            mService.goToNext(filePath);
            AppConstants.CURRENT_PLAY_STATE = EPlayControlType.PLAY;
//            mAdapter.initPalyState(EPlayControlType.PLAY);//初始化按钮状态-正在播放
        } catch (RemoteException e) {
            e.printStackTrace();
            Log.d("MediaPlaybackActivity", "couldn't start playback: " + e);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void sendPlayCount() {
        //开始播放，请求一个统计播放量的接口
        UserModel info = XYJApplication.getUserInfo();
        if (info == null) {
            sendListeneReq(mDianDramaModel.getId(), -1);
        } else {
            long userId = -1;
            try {
                userId = Long.valueOf(info.getUserId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            sendListeneReq(mDianDramaModel.getId(), userId);
        }
    }

    /**
     * 重启播放
     */
    protected void restartPlayBack() {
        if (mService != null) {
            try {
                if (!mService.isPlaying()) {//没有在播放
                    Log.d(TAG, "重新启动播放");
                    mService.play();//播放
                    AppConstants.CURRENT_PLAY_STATE = EPlayControlType.PLAY;
                    startLrcPlay();
                    EventBusUtil.postEvent(new AnimationEvent(true));//左上角动画 启动
                    refreshSeekBar();
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 暂停播放
     */
    @Override
    protected void pausePlayback() {
        try {
            if (mService != null) {
                if (mService.isPlaying()) {
                    AppConstants.CURRENT_DURATION = mDuration;
                    AppConstants.CURRENT_POSITION = mService.position();
                    AppConstants.CURRENT_URL = mService.getPath();
                    AppConstants.CURRENT_PLAY_STATE = EPlayControlType.PAUSE;
                    mService.pause();
                    stopLrcPlay();
                    EventBusUtil.postEvent(new AnimationEvent(false));//左上角动画 暂停
                    cancelRefreshSeekBar();
                }
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 刷新进度条
     */
    protected void refreshSeekBar() {
        Log.d(TAG, "刷新进度条");
        long next = startRefreshProgressHint();
        setIsPlayingRightDrama(true);//刷新进度条
        sendNextRefreshMessage(next);
    }

    /**
     * 取消刷新进度条
     */
    protected void cancelRefreshSeekBar() {
        Log.d(TAG, "取消刷新进度条");
        setIsPlayingRightDrama(false);//刷新进度条
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_drama_play_back:
                onBackPressed();
                break;
            case R.id.rl_drama_play_more:
                SelectMenuDialog dialog = new SelectMenuDialog(mContext);
                dialog.setMenu(new String[]{
                        "我也要唱", "举报"
                }, new SelectMenuDialog.SelectMenuClickListener() {
                    @Override
                    public void onSelectMenuClick(Dialog dialog, View item, int position) {
                        if (XYJApplication.getUserInfo() == null) {//如果未登录，跳转到登录界面
                            IntentManager.getInstance().goLoginActivity(mContext);
                            return;
                        }
                        switch (position) {
                            case 0://我也要唱
                                try {
                                    mService.stop();
                                } catch (RemoteException e) {
                                    e.printStackTrace();
                                }
                                if (StringUtil.isNotEmpty(mDianDramaModel.getAccompanyUrl())) {
                                    mDianDramaModel.setNativeUrl(realNativeUrl);
                                    IntentManager.getInstance().goRecordActivity(mContext, mDianDramaModel);
                                } else {
                                    IntentManager.getInstance().goSingAloneActivity(mContext);
                                }
                                ScreenManager.getInstance().currentActivity().finish();
                                break;
                            case 1://举报
                                report();
                                break;
                        }
                        dialog.dismiss();
                    }
                });
                dialog.show();
                break;
        }
    }

    /**
     * 获取评论列表
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/3/16 9:37
     */

    public void getCommentList(int currentPage) {
        GetCommentListReq getCommentListReq = new GetCommentListReq(mDramaId, 2, Integer.MAX_VALUE, currentPage);
        HttpLoader.getInstance().sendRequest(new GetCommentListHandler(getCommentListReq, new MyHttpResponseListener() {
            @Override
            public void onStart() {
                //去掉加载框，显示自己的加载框
                //TODO
            }

            @Override
            public void onSuccess(Object model) {
                super.onSuccess(model);
                LogUtil.d(TAG, "comment list size :" + ((CommentPageInfoModel) model).getCommentList().size());
                mAdapter.updateCommentList(((CommentPageInfoModel) model).getCommentList());
            }

            @Override
            public void onFail(String msg) {
                super.onFail(msg);
                //显示暂无评论
                //TODO
            }
        }, 0));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isMusicPlaying())
            stopLrcPlay();
        unRegisterEventBus();
    }

    /**
     * 举报
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/3/24 14:50
     */
    public void report() {
        ReportReq reportReq = new ReportReq(mDramaInfo.getUserId(), 1, Integer.valueOf(CommonPreferences.getUserId(mContext)));
        HttpLoader.getInstance().sendRequest(new ReportHandler(reportReq, new MyHttpResponseListener() {
            @Override
            public void onSuccess(Object model) {
                super.onSuccess(model);
                if ((Boolean) model) {
                    ToastUtil.show("举报成功！");
                }
            }
        }, 0));
    }

    /**
     * 用来刷新进度位置
     */
    protected static class MsgHandler extends Handler {
        protected WeakReference<DramaPlayActivity> reference;

        public MsgHandler(DramaPlayActivity activity) {
            reference = new WeakReference<DramaPlayActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            DramaPlayActivity activity = reference.get();
            if (activity == null) {
                return;
            }
            switch (msg.what) {
                case MSG_REFRESH_PROGRESS_POS://自己发送 自己收 又自己发送
                    long next = activity.startRefreshProgressHint();
                    activity.sendNextRefreshMessage(next);
                    break;
            }
            super.handleMessage(msg);
        }
    }

}
